using System;
using System.IO;
using System.Text.Json;
using System.Diagnostics;
using SvgToFontConverter.Models;

namespace SvgToFontConverter.Services
{
    /// <summary>
    /// 引擎配置服务类
    /// </summary>
    public class EngineConfigService
    {
        private const string CONFIG_FILE_NAME = "engine_config.json";
        private readonly string _configFilePath;
        
        public EngineConfigService()
        {
            _configFilePath = Path.Combine(Environment.CurrentDirectory, CONFIG_FILE_NAME);
        }
        
        /// <summary>
        /// 加载引擎配置
        /// </summary>
        /// <returns>引擎配置对象</returns>
        public EngineConfig LoadConfig()
        {
            try
            {
                if (File.Exists(_configFilePath))
                {
                    var json = File.ReadAllText(_configFilePath);
                    var config = JsonSerializer.Deserialize<EngineConfig>(json);
                    if (config != null)
                    {
                        return config;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"加载引擎配置失败: {ex.Message}");
            }
            
            // 返回默认配置
            return CreateDefaultConfig();
        }
        
        /// <summary>
        /// 保存引擎配置
        /// </summary>
        /// <param name="config">要保存的配置</param>
        /// <returns>是否保存成功</returns>
        public bool SaveConfig(EngineConfig config)
        {
            try
            {
                var options = new JsonSerializerOptions
                {
                    WriteIndented = true
                };
                var json = JsonSerializer.Serialize(config, options);
                File.WriteAllText(_configFilePath, json);
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"保存引擎配置失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 验证FontForge配置
        /// </summary>
        /// <param name="config">FontForge配置</param>
        /// <returns>是否有效</returns>
        public bool ValidateFontForgeConfig(FontForgeConfig config)
        {
            if (string.IsNullOrWhiteSpace(config.InstallPath))
                return false;
                
            var ffpythonPath = Path.Combine(config.InstallPath, "ffpython.exe");
            return File.Exists(ffpythonPath);
        }
        
        /// <summary>
        /// 验证Fontello CLI配置
        /// </summary>
        /// <param name="config">Fontello CLI配置</param>
        /// <returns>是否有效</returns>
        public bool ValidateFontelloCliConfig(FontelloCliConfig config)
        {
            // 检查Node.js路径
            if (string.IsNullOrWhiteSpace(config.NodeJsPath))
                return false;
                
            var nodePath = Path.Combine(config.NodeJsPath, "node.exe");
            if (!File.Exists(nodePath))
                return false;
            
            // 检查Fontello CLI项目路径
            if (string.IsNullOrWhiteSpace(config.FontelloCliPath))
                return false;
                
            var packageJsonPath = Path.Combine(config.FontelloCliPath, "package.json");
            if (!File.Exists(packageJsonPath))
                return false;
                
            // 检查是否是fontello-cli项目
            try
            {
                var packageJson = File.ReadAllText(packageJsonPath);
                return packageJson.Contains("fontello-cli");
            }
            catch
            {
                return false;
            }
        }
        
        /// <summary>
        /// 验证SVG2TTF配置
        /// </summary>
        /// <param name="config">SVG2TTF配置</param>
        /// <returns>是否有效</returns>
        public bool ValidateSvg2TtfConfig(Svg2TtfConfig config)
        {
            string nodeCommand;
            
            // 如果指定了Node.js路径，使用指定路径
            if (!string.IsNullOrWhiteSpace(config.NodeJsPath))
            {
                var nodePath = Path.Combine(config.NodeJsPath, "node.exe");
                if (!File.Exists(nodePath))
                {
                    Debug.WriteLine($"Node.js路径无效: {nodePath}");
                    return false;
                }
                nodeCommand = nodePath;
            }
            else
            {
                // 尝试使用全局Node.js安装
                nodeCommand = "node";
            }
            
            // 检查svg2ttf是否已全局安装
            try
            {
                // 首先尝试使用npm list检查全局安装
                using (var npmProcess = new Process())
                {
                    npmProcess.StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = "/c npm list -g svg2ttf --depth=0",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true
                    };
                    
                    // 继承当前进程的环境变量，确保PATH正确设置
                    foreach (System.Collections.DictionaryEntry env in Environment.GetEnvironmentVariables())
                    {
                        npmProcess.StartInfo.EnvironmentVariables[env.Key.ToString()] = env.Value.ToString();
                    }
                    
                    npmProcess.Start();
                    var output = npmProcess.StandardOutput.ReadToEnd();
                    var error = npmProcess.StandardError.ReadToEnd();
                    npmProcess.WaitForExit(10000); // 10秒超时
                    
                    Debug.WriteLine($"npm list 退出码: {npmProcess.ExitCode}");
                    Debug.WriteLine($"npm list 输出: {output}");
                    if (!string.IsNullOrEmpty(error))
                    {
                        Debug.WriteLine($"npm list 错误: {error}");
                    }
                    
                    if (npmProcess.ExitCode == 0 && output.Contains("svg2ttf@"))
                    {
                        Debug.WriteLine("通过npm list检测到svg2ttf");
                        return true;
                    }
                }
                
                Debug.WriteLine("npm list检测失败，尝试Node.js require方式");
                
                // 如果npm list失败，尝试直接require检测
                using (var nodeProcess = new Process())
                {
                    nodeProcess.StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = $"/c \"{nodeCommand}\" -e \"console.log(require('svg2ttf'))\"",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true
                    };
                    
                    // 继承当前进程的环境变量，确保PATH正确设置
                    foreach (System.Collections.DictionaryEntry env in Environment.GetEnvironmentVariables())
                    {
                        nodeProcess.StartInfo.EnvironmentVariables[env.Key.ToString()] = env.Value.ToString();
                    }
                    
                    nodeProcess.Start();
                    var output = nodeProcess.StandardOutput.ReadToEnd();
                    var error = nodeProcess.StandardError.ReadToEnd();
                    nodeProcess.WaitForExit(10000); // 10秒超时
                    
                    Debug.WriteLine($"Node.js require 退出码: {nodeProcess.ExitCode}");
                    Debug.WriteLine($"Node.js require 输出: {output}");
                    if (!string.IsNullOrEmpty(error))
                    {
                        Debug.WriteLine($"Node.js require 错误: {error}");
                    }
                    
                    return nodeProcess.ExitCode == 0;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"SVG2TTF配置验证异常: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 自动检测FontForge路径
        /// </summary>
        /// <returns>检测到的路径，如果未找到则返回空字符串</returns>
        public string AutoDetectFontForgePath()
        {
            var commonPaths = new[]
            {
                @"C:\Program Files (x86)\FontForgeBuilds\bin",
                @"C:\Program Files\FontForgeBuilds\bin",
                @"C:\FontForge\bin",
                @"C:\Program Files (x86)\FontForge\bin",
                @"C:\Program Files\FontForge\bin",
                @"D:\toolplace\FontForgeBuilds\bin"
            };
            
            foreach (var path in commonPaths)
            {
                if (Directory.Exists(path) && File.Exists(Path.Combine(path, "ffpython.exe")))
                {
                    return path;
                }
            }
            
            return string.Empty;
        }
        
        /// <summary>
        /// 自动检测Node.js路径
        /// </summary>
        /// <returns>检测到的路径，如果未找到则返回空字符串</returns>
        public string AutoDetectNodeJsPath()
        {
            var commonPaths = new[]
            {
                @"C:\Program Files\nodejs",
                @"C:\Program Files (x86)\nodejs",
                Environment.GetEnvironmentVariable("ProgramFiles") + "\\nodejs",
                Environment.GetEnvironmentVariable("ProgramFiles(x86)") + "\\nodejs"
            };
            
            foreach (var path in commonPaths)
            {
                if (!string.IsNullOrEmpty(path) && Directory.Exists(path) && File.Exists(Path.Combine(path, "node.exe")))
                {
                    return path;
                }
            }
            
            // 尝试从PATH环境变量中查找
            try
            {
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "where",
                        Arguments = "node",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };
                
                process.Start();
                var output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                
                if (process.ExitCode == 0 && !string.IsNullOrWhiteSpace(output))
                {
                    var nodePath = output.Trim().Split('\n')[0].Trim();
                    if (File.Exists(nodePath))
                    {
                        return Path.GetDirectoryName(nodePath);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"自动检测Node.js路径失败: {ex.Message}");
            }
            
            return string.Empty;
        }
        
        /// <summary>
        /// 创建默认配置
        /// </summary>
        /// <returns>默认引擎配置</returns>
        public EngineConfig CreateDefaultConfig()
        {
            var config = new EngineConfig();
            
            // 尝试自动检测FontForge路径
            var fontForgePath = AutoDetectFontForgePath();
            if (!string.IsNullOrEmpty(fontForgePath))
            {
                config.FontForge.InstallPath = fontForgePath;
                config.FontForge.IsValidated = true;
            }
            
            // 尝试自动检测Node.js路径
            var nodeJsPath = AutoDetectNodeJsPath();
            if (!string.IsNullOrEmpty(nodeJsPath))
            {
                config.FontelloCli.NodeJsPath = nodeJsPath;
                config.Svg2Ttf.NodeJsPath = nodeJsPath;
            }
            
            // 设置默认的Fontello CLI项目路径
            var defaultFontelloPath = Path.Combine(Environment.CurrentDirectory, "..", "开源项目", "fontello-cli-0.6.2");
            if (Directory.Exists(defaultFontelloPath))
            {
                config.FontelloCli.FontelloCliPath = Path.GetFullPath(defaultFontelloPath);
            }
            
            return config;
        }
    }
}